import React, { useState, useRef } from 'react';
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { t } from '@lingui/macro';
import { Button, Dialog, Drawer, Message } from '@alifd/next';
import { useStore } from '@/hooks';
import { uniqueId } from 'lodash';
import { column } from './stores/definitions';
import { observer } from 'mobx-react-lite';
import { toJS } from 'mobx';
import DataForm from './components/DataForm';

const tableId = uniqueId('tauTable-');
const { confirm } = Dialog;

const Dispatcher = () => {
  const { dispatcherStore: store } = useStore();
  const [modal, setModal] = useState([]);
  const dispatchRef = useRef();

  /**
   * @description 处理搜索条件
   * @param {*} params
   */
  const handleOnSearch = (params) => {
    const { ...searchArgs } = params.values;
    store.search = {
      ...searchArgs,
    };
  };

  /**
   * @description 创建调度员  仅限公司控制台
   */
  const handleOpenAdd = () => {
    dispatchRef.current = {};
    setModal(['add']);
  };

  /**
   * @description 打开卡片
   */
  const handleOpenEdit = (r) => {
    dispatchRef.current = r;
    setModal(['edit']);
  };

  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create(toJS(result));
        Message.success({ content: t`创建成功` });
      } catch (e) {
        Message.error({ content: t`创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleDelete = (r) => {
    confirm({
      title: '确认删除该调度员吗?',
      onOk() {
        store.delete(r);
      },
    });
  };

  const handleCancel = () => {
    setModal([]);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={global.isAdmin !== 'admin' ? [
          {
            name: 'btn-addDispatcher',
            title: t`添加调度员`,
            type: 'primary',
            onClick: () => handleOpenAdd(),
          },
        ] : []}
        keywordSearch={{
          // enabled: false,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.dispatch)}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('companyName', { width: 138 }),
            column('extra.dispatcherName', {}),
            column('gender', {}),
            column('mobile', {}),
            column('crDate', {}),
            {
              title: t`操作`,
              dataIndex: 'dispatchNumber',
              width: 180,
              cell: (_, __, dispatch) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenEdit(dispatch)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" style={{ color: 'red' }} onClick={() => handleDelete(dispatch?.username)} >{t`删除`}</Button>
                </>),
            },
          ]}
        />
      </div>
      <Drawer
        visible={!!modal[0]}
        title={modal[0] === 'edit' ? t`编辑调度员` : t`新建调度员`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="650px"
      >
        <DataForm
          dispatchInfo={dispatchRef.current}
          modal={modal}
          onCancel={() => handleCancel()}
          onSubmit={modal[0] === 'edit' ? handleUpdate : handleCreate}
        />
      </Drawer>
    </TauPage>
  );
};

export default observer(Dispatcher);
